package top.meeting.room.common.kit;

import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import top.meeting.room.common.constant.ResultEnum;
import top.meeting.room.common.exceptions.HandlerException;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/7/30
 * FOR : BeanKit
 */
public class BeanKit {
    /**
     * Map转换层Bean，使用泛型免去了类型转换的麻烦。
     *
     * @param <T>
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T map2Bean(Map map, Class<T> clazz) {
        T bean = null;
        try {
            bean = clazz.newInstance();
            BeanUtils.populate(bean, map);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return bean;
    }

    /**
     * jsonStr转化为bean
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Bean(String jsonStr, Class<T> clazz) {
        return JSON.parseObject(jsonStr, clazz);
    }

    /**
     * bean2Map
     *
     * @param object
     * @return
     */
    public static Map<String, String> bean2Map(Object object) {
        try {
            return BeanUtils.describe(object);
        } catch (Exception e) {
            throw new HandlerException(ResultEnum.DATA_ERROR, "表单项转化错误");
        }
    }
}
